#include "stdafx.h"
#include "Speeder.h"

Speeder::Speeder(): m_min(3000),m_max(30000),m_pos(-1)
{

}

Speeder::~Speeder()
{

}

int Speeder::GetSpeed()
{
	return (m_max-m_min) * m_pos / 100;
}

void Speeder::SetSpeed(int speed)
{
	speed = max(m_min, speed);
	speed = min(m_max, speed);
	m_pos = (speed-m_min) * 100 / (m_max-m_min);
}

void Speeder::DrawSpeeder(CDC *pDC)
{
	if(IsValid())
	{
		//draw frame
		CPen *pOldPen = pDC->SelectObject(&Sheet::txpen);
		pDC->SetTextColor(Sheet::colorText);
		pDC->MoveTo(m_bounding.left, m_bounding.top);
		pDC->LineTo(m_bounding.right-1, m_bounding.top);
		pDC->LineTo(m_bounding.right-1, m_bounding.bottom-1);
		pDC->LineTo(m_bounding.left, m_bounding.bottom-1);
		pDC->LineTo(m_bounding.left, m_bounding.top);
		pDC->SelectObject(pOldPen);

		//draw mark
		CRect rect = GetMarkRect();
		pDC->FillSolidRect(&rect, RGB(232,242,194));
	}
}

void Speeder::InvalidateMark(HWND hwnd)
{
	CRect rect = m_bounding;
	rect.DeflateRect(1,1,1,1);
	::InvalidateRect(hwnd, &rect, TRUE);
}

void Speeder::Invalidate(HWND hwnd)
{
	CRect rect = m_bounding;
	::InvalidateRect(hwnd, &rect, TRUE);
}

int Speeder::GetLength()
{
	return m_bounding.Height() - GetMarkSize().cy;
}

int Speeder::GetTopPos()
{
	return m_bounding.top + GetMarkSize().cy/2;
}

CSize Speeder::GetMarkSize()
{
	return CSize(m_bounding.Width()*0.84,
                m_bounding.Height()*0.075);
}

CRect Speeder::GetMarkRect()
{
	int cx = GetMarkSize().cx,
		 cy = GetMarkSize().cy,
		 offset = cy/2;

	CPoint o( (m_bounding.left+m_bounding.right)/2,
				  m_bounding.top + offset + GetLength()*m_pos/100);

	return CRect(o.x-cx/2, o.y-offset, o.x+cx/2, o.y+offset);
}

bool Speeder::OnLButtonDown(CPoint point)
{
	if(IsValid())
	{
		if(m_bounding.PtInRect(point)){
			m_pos = (point.y - GetTopPos())*100/GetLength();
			m_pos = max(0, m_pos);
			m_pos = min(m_pos, 100);
			return true;
		}
	}

	return false;
}

bool Speeder::OnRButtonDown(CPoint point)
{
	if(IsValid())
	{
		if( m_bounding.PtInRect(point) ){
			Disable();
			return true;
		}
	}

	return false;
}

